<?php

function fwrite_stream($fp, $string) {
    for ($written = 0; $written < strlen($string); $written += $fwrite) {
    	$str = substr($string, $written);
        $fwrite = socket_send($fp, $str, strlen($str), MSG_DONTROUTE);
        if ($fwrite === false) {
            return $written;
        }
    }
    return $written;
}

//发起一个分词请求
function request($socket, $msg)
{
	$msg = (strlen($msg) + 2) . "\r\n" . $msg;
	$len = fwrite_stream($socket, $msg);
	echo "成功写入 $len\r\n";

	$line = trim(socket_read($socket, 2048));
	$array = explode("\r\n", $line, 2);
	$len = strlen($array[0]) + $array[0];
	$needLen = $len - strlen($line);
	$line = $array[1];
	if($needLen>0) {
		$tmpStr .= socket_read($socket, $needLen);
		if($tmpStr === false) {
			die('数据读取失败');
		}
		$line .= $tmpStr;
	}
	return $line;
}

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$result = socket_connect($socket, '127.0.0.1', 9999);
if(!$result) {
    die("无法连接");
}

$msg = "一开始strtol()会扫描参数nptr字符串，跳过前面的空格字符，直到遇上数字或正负符号才开始做转换，再遇到非数字或字符串结束时结束转换，并将转换数值返回。参数endptr指向停止转换的位置，若字符串nptr的所有字符都成功转换成数字则endptr指向串结束符''。判断是否转换成功，应检查**endptr是否为";

$startTime = time();
$count = 500000;
for ($i=0; $i < $count; $i++) {
	echo "第 $i 次请求\r\n";
	$line = request($socket, $msg);
	echo "结果  :" . $line . "\r\n";
}
$runTime = time() - $startTime;
echo "本次测试用时 {$runTime}s, QPS:" . ($count/$runTime) . "\r\n";







